﻿using System;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace SlamCms.Web.Mvc
{
	public class JsonpResult : NewtonJsonResult
	{
		public JsonpResult()
		{
		}

		public JsonpResult(object data)
		{
			this.Data = data;
		}

		public override void ExecuteResult(ControllerContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");

			var request = context.HttpContext.Request;
			var response = context.HttpContext.Response;
			
			if (!string.IsNullOrEmpty(this.ContentType))
				response.ContentType = this.ContentType;
			else
				response.ContentType = "application/javascript";

			if (this.ContentEncoding != null)
				response.ContentEncoding = this.ContentEncoding;

			var callback = request["callback"] ?? "callback";

			var serializedData = "{}"; 
			
			if (this.Data != null)
				serializedData = JsonConvert.SerializeObject(this.Data);

			response.Write(string.Format("{0}({1})", callback, serializedData));
		}
	}
}
